import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { Line, Column, Pie } from '@ant-design/plots';
import { message } from 'antd';
import { useEffect, useState } from 'react';
import { useModel } from 'umi';
import { getDailyRevenue } from '../service';
import type { DailyRevenueType } from '../types.d';
import { Role } from '@/utils/types.d';
import { ProFormSelect, ProCard } from '@ant-design/pro-components';
import { queryCompanies } from '@/pages/SystemUser/service';
import PicCard from './components/PicCard';
import * as moment from 'moment';

const defaultData: DailyRevenueType = {
  amounts: [],
  orders: [],
  tActualAmount: 0,
  tArrearAmount: 0,
  tRecoveryAmount: 0,
  tFreeOrder: 0,
  tCharedOrder: 0,
  tArrearOrder: 0,
  tExceptOrder: 0,
  tTotalOrder: 0,
  tTotalAmount: 0,
  tPayableAmount: 0,
  tPlateAmount: 0,
  tChargePlatedOrder: 0,
  tCancelAmount: 0,
  tCancelOrder: 0,
  tRefundAmount: 0,
  tMemberAmount: 0,
  tMemberOrder: 0,
  tLossAmount: 0,
  tPaymentAmount: 0,
};
const RevenueDaily = () => {
  const { initialState } = useModel('@@initialState');
  const currUser = initialState?.currentUser;
  const isAdmin = currUser?.role === Role.ADMIN;
  const [ownerId, setOwnerId] = useState<string>(currUser?.ownerId || '');
  const [data, setData] = useState<DailyRevenueType>(defaultData);
  const [revenueTime, setRevenueTime] = useState<string>('-');
  const [nowTime, setNowTime] = useState<string>('-');

  useEffect(() => {
    getDailyRevenue(ownerId).then((res) => {
      if (res.success) {
        setData(res.data as DailyRevenueType);
        setRevenueTime(moment().format('YYYY-MM-DD HH:00'));
        setNowTime(moment().format('YYYY-MM-DD HH:mm'));
        return;
      } else {
        message.error({ key: 'daily_revenue', content: res.message });
        setNowTime(moment().format('YYYY-MM-DD HH:mm'));
        setData(defaultData);
        return;
      }
    });
  }, [ownerId]);
  return (
    <PageHeaderWrapper>
      {isAdmin && (
        <ProCard
          style={{
            margin: '2px 0',
          }}
        >
          <ProFormSelect
            name="ownerId"
            label="统计公司"
            debounceTime={300}
            showSearch
            fieldProps={{
              onChange: (val) => setOwnerId(val),
              style: {
                width: 280,
                margin: 0,
              },
            }}
            placeholder="请选择要统计的公司"
            request={(val) => queryCompanies(val.keyWords)}
          />
        </ProCard>
      )}
      <ProCard bodyStyle={{ display: 'flex', justifyContent: 'space-between' }}>
        <PicCard
          picSrc="/images/payable.svg"
          title="当日应收金额"
          tooltip="当日产生的停车订单(在当日驶出车辆的订单)的应收总金额"
          value={`¥${data.tPayableAmount.toFixed(2)}`}
          updateTime={revenueTime}
          unit={'元'}
        />

        <PicCard
          picSrc="/images/actuall.svg"
          title="当日实收金额"
          tooltip="当日支付记录总金额(包括实时订单和欠费订单)"
          value={`¥${data.tPaymentAmount.toFixed(2)}`}
          updateTime={revenueTime}
          unit={'元'}
        />
        <PicCard
          picSrc="/images/totalOrder.svg"
          title="当日订单总数"
          tooltip="当日产生的停车订单(在当日驶出车辆的订单)总数"
          value={data.tTotalOrder}
          updateTime={revenueTime}
          unit={'单'}
        />
        <PicCard
          picSrc="/images/chargeOrder.svg"
          title="当日收费订单"
          tooltip="当日产生的非免费停车订单(在当日驶出车辆的订单)总数"
          value={data.tCharedOrder}
          updateTime={revenueTime}
          unit={'单'}
        />
      </ProCard>
      <ProCard bodyStyle={{ display: 'flex', justifyContent: 'space-between', paddingTop: 0 }}>
        {/* <PicCard
          picSrc="/images/refund.svg"
          title="退款金额"
          value={`¥${data.tRefundAmount.toFixed(2)}`}
          updateTime={revenueTime}
          unit={'元'}
        /> */}

        <PicCard
          picSrc="/images/cancel.svg"
          title="今日损益金额"
          value={`-¥${data.tLossAmount.toFixed(2)}`}
          updateTime={nowTime}
          tooltip="当日因更改订单时间/退款/作废订单造成的损失金额"
          unit={'元'}
        />
        <PicCard
          picSrc="/images/cancelOrder.svg"
          title="作废订单数"
          value={data.tCancelOrder}
          updateTime={revenueTime}
          unit={'单'}
        />
        <PicCard
          hide
          picSrc="/images/cancelOrder.svg"
          title=""
          value={0}
          updateTime={''}
          unit={''}
        />
        <PicCard
          hide
          picSrc="/images/cancelOrder.svg"
          title=""
          value={0}
          updateTime={''}
          unit={''}
        />
      </ProCard>
      <ProCard
        style={{
          margin: '8px 0',
        }}
        ghost
        gutter={8}
      >
        <ProCard colSpan="65%">
          <Column
            // data={data.amounts
            //   .filter((item) => {
            //     if (item.hour > 8) return true;
            //     if (item.value > 0) return true;
            //     return false;
            //   })
            //   .sort((a, b) => a.hour - b.hour)}
            data={data.amounts.sort((a, b) => a.hour - b.hour)}
            xField="hour"
            yField="value"
            xAxis={{
              label: {
                formatter: (v) => `${v}时`,
              },
            }}
            yAxis={{
              label: {
                formatter: (v) => `${v}元`,
              },
            }}
            seriesField="type"
            isGroup
            label={{
              // 可手动配置 label 数据标签位置
              position: 'middle',
              // 可配置附加的布局方法
              layout: [
                // 柱形图数据标签位置自动调整
                {
                  type: 'interval-adjust-position',
                }, // 数据标签防遮挡
                {
                  type: 'interval-hide-overlap',
                }, // 数据标签文颜色自动调整
                {
                  type: 'adjust-color',
                },
              ],
            }}
          />
        </ProCard>
        <ProCard colSpan="35%">
          <Pie
            data={[
              {
                type: '缴费率',
                value: Number(data.tActualAmount.toFixed(2)),
              },
              {
                type: '欠费率',
                value: Number(data.tArrearAmount.toFixed(2)),
              },
            ]}
            angleField="value"
            colorField="type"
            appendPadding={10}
            color={['#3673E8', '#61B8FF']}
            radius={0.8}
            legend={{
              itemName: {
                formatter(text, item) {
                  const val = item.name == '缴费率' ? data.tActualAmount : data.tArrearAmount;
                  const total = data.tActualAmount + data.tArrearAmount || 0;
                  const rate = total == 0 ? '0.00' : ((val / total) * 100).toFixed(2);
                  return `${text} ${rate}%`;
                },
                style: {
                  fontSize: 16,
                },
              },
              offsetX: -20,
            }}
            label={{
              type: 'inner',
              content: '',
            }}
            pieStyle={{ lineWidth: 0 }}
          />
        </ProCard>
      </ProCard>
      <ProCard
        style={{
          margin: '8px 0',
        }}
      >
        <Line
          data={data.orders.sort((a, b) => a.hour - b.hour)}
          xField="hour"
          yField="value"
          seriesField="type"
          xAxis={{
            label: {
              formatter: (v) => `${v}时`,
            },
          }}
          yAxis={{
            label: {
              formatter: (v) => `${v}个`,
            },
          }}
          smooth={true}
        />
      </ProCard>
    </PageHeaderWrapper>
  );
};

export default RevenueDaily;
